package com.app.art.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class RabbitMQConfig {

    public static final String QUEUE_NAME = "my.queue";
    public static final String EXCHANGE_NAME = "my.exchange";
    public static final String ROUTING_KEY = "my.routing.key";

    public static final String QUEUE_DEAD = "my.dlq";
    public static final String EXCHANGE_DEAD = "dlx.exchange";
    public static final String ROUTING_KEY_DEAD = "dlq.routing.key";


    // 正常队列绑定死信交换机
    @Bean
    public Queue myQueue() {
        return QueueBuilder.durable(QUEUE_NAME)
                .withArgument("x-dead-letter-exchange", EXCHANGE_DEAD)
                .withArgument("x-dead-letter-routing-key", ROUTING_KEY_DEAD)
                .build();
    }

    @Bean
    public DirectExchange myExchange() {
        return new DirectExchange(EXCHANGE_NAME, true, false);
    }

    @Bean
    public Binding binding(Queue myQueue, DirectExchange myExchange) {
        return BindingBuilder.bind(myQueue).to(myExchange).with(ROUTING_KEY);
    }

    // 可选：配置消息转换器（如使用 JSON）
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    // 死信队列
    // 死信交换机和队列
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(EXCHANGE_DEAD);
    }

    @Bean
    public Queue dlqQueue() {
        return new Queue(QUEUE_DEAD, true);
    }

    @Bean
    public Binding dlqBinding() {
        return BindingBuilder.bind(dlqQueue()).to(dlxExchange()).with(ROUTING_KEY_DEAD);
    }


    @Bean
    public RabbitTemplate dlxMessageConverter(ConnectionFactory connectionFactory) {
        log.info("创建 RabbitTemplate {}",connectionFactory);
        RabbitTemplate template = new RabbitTemplate(connectionFactory);

        // 开启 Confirm 回调
        template.setConfirmCallback((correlationData, ack, cause) -> {
            String id = correlationData != null ? correlationData.getId() : "unknown";
            if (ack) {
                log.info("🟢 消息 [" + id + "] 已成功到达 Exchange");
                // 可更新数据库：message_status = 'sent'
            } else {
                log.info("🔴 消息 [" + id + "] 发送失败: " + cause);
                // 可记录日志、触发告警、加入重试队列
            }
        });

        return template;
    }
}
